/*
 * @Author: jingfuu@163.com
 * @Date: 2024-11-18 13:02:38
 * @LastEditTime: 2024-12-11 15:18:00
 * @Description: 部门接口
 */
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { DeptService } from '../service/DeptService';
import {
  Body,
  Controller,
  Delete,
  Get,
  Logger,
  Param,
  Post,
  Put,
  Query,
} from '@nestjs/common';
import { DeptDto } from '../dto/DeptDto';
import DeptQueryParam from '../param/DeptQueryParam';
import PageResult from 'src/common/PageResult';
import { R } from 'src/common/R';
import { PreAuthorize } from 'src/common/decorator/pre-authorize.decorator';
import { Log } from 'src/common/decorator/log';
import BusinessType from 'src/common/enum/BusinessType';

@ApiTags('部门接口')
@Controller('system/dept')
class DeptController {
  private readonly logger = new Logger(DeptController.name);

  constructor(private deptService: DeptService) {}

  @PreAuthorize('system:dept:list')
  @ApiOperation({ summary: '分页查询部门列表' })
  @Get('/list')
  async findRoleList(@Query() param: DeptQueryParam): Promise<R<DeptDto[]>> {
    this.logger.log('query role list start, param:' + JSON.stringify(param));
    param.pageSize = 1000;
    const result: PageResult<DeptDto> = await this.deptService.list(param);
    return R.ok(result.rows);
  }

  @PreAuthorize('system:dept:query')
  @ApiOperation({ summary: '获取部门详情' })
  @Get('/:id(\\d+)')
  async getRole(@Param('id') id: number): Promise<R<DeptDto>> {
    return R.ok(await this.deptService.getById(id));
  }

  @ApiOperation({ summary: '获取部门树，排除自己供修改使用' })
  @Get('/list/exclude/:id(\\d+)')
  async getExcludeDepts(@Param('id') id: number): Promise<R<DeptDto[]>> {
    return R.ok(await this.deptService.getExcludeDepts(id));
  }

  @Log({ title: '部门管理', businessType: BusinessType.UPDATE })
  @PreAuthorize('system:dept:edit')
  @ApiOperation({ summary: '修改部门' })
  @Put()
  async updateDept(@Body() dept: DeptDto): Promise<R<void>> {
    await this.deptService.updateDept(dept);
    return R.ok();
  }

  @Log({ title: '部门管理', businessType: BusinessType.INSERT })
  @PreAuthorize('system:dept:add')
  @ApiOperation({ summary: '新增部门' })
  @Post()
  async addDept(@Body() dept: DeptDto): Promise<R<void>> {
    await this.deptService.addDept(dept);
    return R.ok();
  }

  @Log({ title: '部门管理', businessType: BusinessType.DELETE })
  @PreAuthorize('system:dept:remove')
  @ApiOperation({ summary: '删除部门' })
  @Delete('/:id')
  async deleteDept(@Param('id') id: string): Promise<R<any>> {
    if (id.indexOf(',') > -1) {
      for (const item of id.split(',')) {
        await this.deptService.deleteDpet(Number.parseInt(item));
      }
    } else {
      await this.deptService.deleteDpet(Number.parseInt(id));
    }
    return R.ok();
  }
}
export default DeptController;
